package com.ruoyi.project.modules.category.service.impl;

import com.ruoyi.common.core.domain.Ztree;
import com.ruoyi.common.core.text.Convert;
import com.ruoyi.common.json.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.modules.businessSystem.domain.BusinessSystem;
import com.ruoyi.project.modules.businessSystem.mapper.BusinessSystemMapper;
import com.ruoyi.project.modules.category.domain.Category;
import com.ruoyi.project.modules.category.mapper.CategoryMapper;
import com.ruoyi.project.modules.category.service.ICategoryService;
import com.ruoyi.project.modules.page.mapper.PageMapper;
import com.ruoyi.project.modules.usage.mapper.UsageMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 分类体系Service业务层处理
 *
 * @author smallrain
 * @date 2021-11-03
 */
@Service
public class CategoryServiceImpl implements ICategoryService {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private PageMapper pageMapper;
    @Resource
    private BusinessSystemMapper businessSystemMapper;
    @Resource
    private UsageMapper usageMapper;

    /**
     * 查询分类体系
     *
     * @param id 分类体系主键
     * @return 分类体系
     */
    @Override
    public Category selectCategoryById(Long id) {
        return categoryMapper.selectCategoryById(id);
    }

    /**
     * 查询分类体系列表
     *
     * @param category 分类体系
     * @return 分类体系
     */
    @Override
    public List<Category> selectCategoryList(Category category) {
        return categoryMapper.selectCategoryList(category);
    }

    /**
     * 新增分类体系
     *
     * @param category 分类体系
     * @return 结果
     */
    @Override
    public synchronized int insertCategory(Category category) {
        category.setCreateTime(DateUtils.getNowDate());
        String code = null;
        if (category.getParentId() != null) {
            Category parent = this.selectCategoryById(category.getParentId());
            category.setLevel((Integer.parseInt(parent.getLevel()) + 1) + "");
            String maxCode = this.categoryMapper.getMaxCodeByParentId(category.getParentId());
            // code = 父Code + 序列号
            if (maxCode == null) {
                code = String.format("%s%s", parent.getCode(), "000001");
            } else {
                maxCode = maxCode.substring(maxCode.length() - 6);
                int seq = Integer.parseInt(maxCode) + 1;
                code = String.format("%s%06d", parent.getCode(), seq);
            }
            category.setSystemType(parent.getSystemType());
        } else {
            category.setLevel("1");
            // code = systemType + 序列号
            String maxCode = this.categoryMapper.getMaxCode(category.getSystemType(), category.getLevel());
            if (maxCode == null) {
                code = String.format("%s%s", category.getSystemType(), "000001");
            } else {
                maxCode = maxCode.substring(maxCode.length() - 6);
                int seq = Integer.parseInt(maxCode) + 1;
                code = String.format("%s%06d", category.getSystemType(), seq);
            }
        }
        category.setCode(code);
        return categoryMapper.insertCategory(category);
    }

    /**
     * 修改分类体系
     *
     * @param category 分类体系
     * @return 结果
     */
    @Override
    @Transactional
    public synchronized int updateCategory(Category category) {
        category.setUpdateTime(DateUtils.getNowDate());
        Category category1 = this.selectCategoryById(category.getId());
        boolean flag = false;
        if (!category1.getParentId().equals(category.getParentId())) {
            flag = true;
        }
        if (category.getParentId() != null) {
            Category parent = this.selectCategoryById(category.getParentId());
            category.setLevel((Integer.parseInt(parent.getLevel()) + 1) + "");
            category.setSystemType(parent.getSystemType());
            if (flag) {
                String maxCode = this.categoryMapper.getMaxCodeByParentId(category.getParentId());
                // code = 父Code + 序列号
                String code = null;
                if (maxCode == null) {
                    code = String.format("%s%s", parent.getCode(), "000001");
                } else {
                    maxCode = maxCode.substring(maxCode.length() - 6);
                    int seq = Integer.parseInt(maxCode) + 1;
                    code = String.format("%s%06d", parent.getCode(), seq);
                }
                category.setCode(code);
            }
        } else {
            category.setLevel("1");
            if (flag) {
                String code = null;
                // code = systemType + 序列号
                String maxCode = this.categoryMapper.getMaxCode(category.getSystemType(), category.getLevel());
                if (maxCode == null) {
                    code = String.format("%s%s", category.getSystemType(), "000001");
                } else {
                    maxCode = maxCode.substring(maxCode.length() - 6);
                    int seq = Integer.parseInt(maxCode) + 1;
                    code = String.format("%s%06d", category.getSystemType(), seq);
                }
                category.setCode(code);
            }
        }
        if (flag) {
            if (category.getSystemType().equals("2")) {
                pageMapper.updateCategoryCode(category.getId(), category.getCode());
            } else if (category.getSystemType().equals("1")) {
                this.businessSystemMapper.updateCategoryCode(category.getId(), category.getCode());
            } else {
                this.usageMapper.updateCategoryCode(category.getId(), category.getCode());
            }
        }
        return categoryMapper.updateCategory(category);
    }

    /**
     * 批量删除分类体系
     *
     * @param ids 需要删除的分类体系主键
     * @return 结果
     */
    @Override
    public int deleteCategoryByIds(String ids) {
        return categoryMapper.deleteCategoryByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除分类体系信息
     *
     * @param id 分类体系主键
     * @return 结果
     */
    @Override
    public int deleteCategoryById(Long id) {
        return categoryMapper.deleteCategoryById(id);
    }

    /**
     * 查询分类体系树列表
     *
     * @return 所有分类体系信息
     */
    @Override
    public List<Ztree> selectCategoryTree() {
        List<Category> categoryList = categoryMapper.selectCategoryList(new Category());
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Category category : categoryList) {
            Ztree ztree = new Ztree();
            ztree.setId(category.getId());
            ztree.setpId(category.getParentId());
            ztree.setName(category.getCategoryName());
            ztree.setTitle(category.getCategoryName());
            ztree.setCode(category.getCode());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    @Override
    public List<Ztree> selectCategoryTree2(String type) {
        Category category1 = new Category();
        category1.setSystemType(type);
        List<Category> categoryList = categoryMapper.selectCategoryList(category1);
        List<Ztree> ztrees = new ArrayList<Ztree>();
        for (Category category : categoryList) {
            Ztree ztree = new Ztree();
            ztree.setId(category.getId());
            ztree.setpId(category.getParentId());
            ztree.setName(category.getCategoryName());
            ztree.setTitle(category.getCategoryName());
            ztree.setCode(category.getCode());
            ztrees.add(ztree);
        }
        return ztrees;
    }

    @Override
    public List<Ztree> selectCategoryTreeForContainsObject(String type) {
        Category category = new Category();
        category.setSystemType(type);
        List<Category> categoryList = categoryMapper.selectCategoryList(category);
        if (null == categoryList || categoryList.size() == 0) {
            return null;
        }
        List<Ztree> ztrees = new ArrayList<>(categoryList.size());
        categoryList.stream().forEach(a -> {
            Ztree ztree = new Ztree();
            ztree.setId(a.getId());
            ztree.setpId(a.getParentId());
            ztree.setName(a.getCategoryName());
            ztree.setTitle(a.getCategoryName());
            ztree.setCode(a.getCode());
            JSONObject attribute = new JSONObject();
            attribute.put("type", 1);
            ztree.setAttribute(attribute);
            ztrees.add(ztree);
            if (null == a.getParentId()) {
                return;
            }
            // 验证节点是否叶子节点
            int cnt = categoryMapper.selectCategoryCountByParentId(a.getId());
            if (cnt > 0) {
                return;
            }
            BusinessSystem businessSystem = new BusinessSystem();
            businessSystem.setCategoryId(a.getId());
            List<BusinessSystem> bsList = businessSystemMapper.selectBusinessSystemList(businessSystem);
            if (null == bsList || bsList.size() == 0) {
                return;
            }
            bsList.forEach(b -> {
                Ztree ztreeBs = new Ztree();
                ztreeBs.setId(b.getId());
                ztreeBs.setpId(a.getId());
                ztreeBs.setName(b.getBusinessSystemName());
                ztreeBs.setTitle(b.getBusinessSystemName());
                ztreeBs.setCode(a.getCode());
                JSONObject attributeBs = new JSONObject();
                attributeBs.put("type", 2);
                ztreeBs.setAttribute(attributeBs);
                ztrees.add(ztreeBs);
            });
        });
        return ztrees;
    }
}
